package org.epidroid.epidroid.androsoul.ui.contactimport;

import java.util.List;

import org.epidroid.epidroid.R;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

public class ContactImportAdapter extends ArrayAdapter<ContactImportItem> {

	private List<ContactImportItem> _items;
	private Context _context;

	public ContactImportAdapter(Context context, int textViewResourceId,
			List<ContactImportItem> objects) {
		super(context, textViewResourceId, objects);
		_context = context;
		_items = objects;
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {

		View v = convertView;
		if (v == null) {
			LayoutInflater inflater = (LayoutInflater) _context
					.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
			v = inflater.inflate(R.layout.androsoul_contact_import_item, null);
		}
		final ContactImportItem m = this._items.get(position);

		TextView content = (TextView) v
				.findViewById(R.id.androsoul_contact_import_item_title);
		content.setText(m.get_name());

		final CheckBox bCheck = (CheckBox) v
				.findViewById(R.id.androsoul_contact_import_checkbox);

		final LinearLayout v_ = (LinearLayout) v
				.findViewById(R.id.androsoul_contact_import_wrapper);
		bCheck.setOnCheckedChangeListener(new OnCheckedChangeListener() {

			@Override
			public void onCheckedChanged(CompoundButton buttonView,
					boolean isChecked) {
				m.setSelected(isChecked);
				// TODO: does not work
				if (isChecked) {
					v_.setBackgroundColor(0x000000);
				} else {
					v_.setBackgroundColor(0x333333);
				}
			}
		});

		bCheck.setText(m.get_login());
		bCheck.setTag(m.get_login());
		bCheck.setChecked(true);
		// bCheck.setOnClickListener(this);

		ImageView image = (ImageView) v
				.findViewById(R.id.androsoul_contact_import_item_image);

		if (m.get_photo() == null)
			image.setImageResource(R.drawable.unknownbuddy);
		else {
			image.setImageBitmap(m.get_photo());
		}

		v.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				bCheck.toggle();
			}
		});

		return (v);
	}
}
